<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Layout\Content;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ConsultingController extends Controller
{
    /**
     * 获取医生咨询时间
     */
    public function getConsultingTime(){
        $userId= Auth::guard('admin')->user()->id;
        //获取医生ID
        $doctor = DB::table('doctor')->select(['id','is_consulting'])->where('admin_user_id',$userId)->first();
        if ( empty($doctor) ) return response()->error("PARAM_ERROR");
        //获取咨询时间
        $consultingTime = DB::table('consulting_time')->where('doctor_id',$doctor->id)->where('status',1)->get()->toArray();
        if ( !empty($consultingTime) ) {
            $weeks_type = implode(',',array_column($consultingTime,'weeks_type'));
            $consultingTime = [
                'weeks_type'=> $weeks_type,
                'start_time' => $consultingTime[0]->start_time,
                'end_time' => $consultingTime[0]->end_time,
            ];
        }
        $data = [
            'list'          => $consultingTime,
            'doctor_id'     =>$doctor->id,
            'is_consulting' => $doctor->is_consulting
        ];
        return response()->success($data);
    }

    /**
     * 设置医生咨询时间
     */
    public function setConsultingTime(Request $request){
        $is_consulting = $request->input('is_consulting');
        $doctor_id = $request->input('doctor_id');
        $weeks_type = $request->input('weeks_type');
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        if ( !isset($_REQUEST['is_consulting']) )  return response()->error("PARAM_EMPTY");
        //判断是否开启
        if ( $is_consulting == 1 ) {
            if ( empty($doctor_id) || empty($weeks_type) || empty($start_time) || empty($end_time) ) return response()->error("PARAM_EMPTY");
            DB::beginTransaction();
            try{
                $update = DB::table('doctor')->where('id',$doctor_id)->update(['is_consulting'=>1]);
                if ( empty($update) && $update !== 0 ) throw new \Exception('UPDATE_FAILURE');
                //删除医生咨询时间设置数据
                $delete = DB::table('consulting_time')->where('doctor_id',$doctor_id)->delete();
                if ( empty($delete) && $delete !== 0 ) throw new \Exception('DELETE_FAILURE');
                //添加数据
                $consultingTimeInsertArr = [];
                $weeks_type = explode(',',$weeks_type);
                $dateTime = date('Y-m-d H:i:s',time());
                $item = [
                    'doctor_id' => $doctor_id,
                    'start_time'=> $start_time,
                    'end_time'  => $end_time,
                    'created_at'=> $dateTime,
                    'updated_at'=> $dateTime,
                ];
                foreach ( $weeks_type as $value ) {
                    $item['weeks_type'] = $value;
                    array_push($consultingTimeInsertArr,$item);
                }
                $insert = DB::table('consulting_time')->insert($consultingTimeInsertArr);
                if ( empty($insert) ) throw new \Exception('ADD_FAILURE');
                DB::commit();
            }catch (\Exception $e){
                DB::rollBack();
                return response()->error($e->getMessage());
            }
        }else{
            //修改医生表咨询开启状态
            $status = DB::table('doctor')->where('id',$doctor_id)->update(['is_consulting'=>0]);
            if ( empty($status) && $status !== 0 ) return response()->error("UPDATE_FAILURE");
        }
        return response()->success();
    }

    /**
     * 获取到图文问诊列表
     */
    public function getDiagnoseList(){
        $userId= Auth::guard('admin')->user()->id;
        //获取医生ID
        $doctor = DB::table('doctor')->select(['id','is_consulting'])->where('admin_user_id',$userId)->first();
        if ( empty($doctor) ) return response()->error("PARAM_ERROR");
        $diagnoseData = DB::table('diagnose')->where('doctor_id',$doctor->id)->where('group_id',0)->where('type',2)->where(function ($query) {
            $query->where('status',1)->orWhere('status',3);
        })->get();
        return response()->success($diagnoseData);
    }

    /**
     * 获取到图文详情
     */
    public function getDiagnose(Request $request){
        $id = $request->input('id');
        if ( empty($id) ) return response()->error("PARAM_EMPTY");
        $diagnoseData = DB::table('diagnose AS D')->select(['D.*','C.name','C.position','C.photo','U.name AS u_name','U.avatar'])
                        ->leftJoin('doctor AS C','D.doctor_id','=','C.id')
                        ->leftJoin('users AS U','D.user_id','=','U.id')
                        ->where('D.id',$id)->orWhere('D.group_id',$id)->orderBy('D.created_at','ASC')->get();
        $data = [
            'list'  => $diagnoseData,
            'domain'=> env('MINI_APP_DOMAIN'),
            'app_domain'=>env('APP_DOMAIN')
        ];
        return response()->success($data);
    }

    /**
     * 医生回复
     */
    public function doctorReply(Request $request){
        $id = $request->input('id');
        $content = $request->input('content');
        if ( empty($id) || empty($content) ) return response()->error("PARAM_EMPTY");
        $userId= Auth::guard('admin')->user()->id;
        //获取医生ID
        $doctor = DB::table('doctor')->select(['id','is_consulting'])->where('admin_user_id',$userId)->first();
        if ( empty($doctor) ) return response()->error("PARAM_ERROR");
        //查询数据
        $diagnoseGet = DB::table('diagnose')->where('id',$id)->where('type',2)->where('group_id',0)->where('doctor_id',$doctor->id)->first();
        if ( empty($diagnoseGet) ) return response()->error("PARAM_ERROR");
        $date = date('Y-m-d H:i:s',time());
        $replyInsertArr = [
            'user_id'           => $diagnoseGet->user_id,
            'doctor_id'         => $doctor->id,
            'group_id'          => $id,
            'initiator_identity'=> 1,
            'type'              => 2,
            'content'           => $content,
            'created_at'        => $date,
            'updated_at'        => $date,
        ];
        DB::beginTransaction();
        try{
            $replyInsert = DB::table('diagnose')->insert($replyInsertArr);
            if ( empty($replyInsert) ) throw new \Exception('ADD_FAILURE');
            $save = DB::table('diagnose')->where('id',$id)->update(['status'=>2]);
            if ( empty($save) ) throw new \Exception('ADD_FAILURE');
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->error($e->getMessage());
        }
        return response()->success();
    }

    /**
     * 获取当前医生的统计数据
     */
    public function statistics(Request $request){
        $userId= Auth::guard('admin')->user()->id;
        //获取医生ID
        $doctor = DB::table('doctor')->select(['id','is_consulting'])->where('admin_user_id',$userId)->first();
        if ( empty($doctor) ) return response()->error("PARAM_ERROR");
        //累计咨询人数
        $start_time = date('Y-m-d '.'00:00:00',time());
        $end_time = date('Y-m-d '.'23:59:59',time());
        $sql = "(SELECT id FROM in_diagnose WHERE doctor_id = {$doctor->id} AND created_at >= '{$start_time}' AND created_at <= '{$end_time}' AND group_id = 0 GROUP BY user_id) AS D";
        $consultingAll = DB::table(DB::raw($sql))->count();
        //获取已处理的
        $sql = "(SELECT id FROM in_diagnose WHERE doctor_id = {$doctor->id} AND created_at >= '{$start_time}' AND created_at <= '{$end_time}' AND group_id = 0 AND ((type=2 AND status=2) OR (type=1)) GROUP BY user_id) AS D";
        $resolved = DB::table(DB::raw($sql))->count();
        //未处理
        $sql = "(SELECT id FROM in_diagnose WHERE doctor_id = {$doctor->id} AND created_at >= '{$start_time}' AND created_at <= '{$end_time}' AND group_id = 0 AND type=2 AND (status=1 OR status=3)  GROUP BY user_id) AS D";
        $notsolved = DB::table(DB::raw($sql))->count();
        $data = [
            'consulting'    => $consultingAll,
            'resolved'      => $resolved,
            'notsolved'     => $notsolved
        ];
        return response()->success($data);
    }
}